package controllers.inapi

import javax.inject.{Inject, Singleton}

import cn.socialcredits.activity.business.{ActivityService, EmailService}
import cn.socialcredits.activity.data.domain.RegisterActivity
import controllers.BaseController
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}

@Singleton
class Activities @Inject()(activityService: ActivityService,
                           emailService: EmailService) extends Controller with BaseController {
  logger.info(getClass.getSimpleName + " run")

  def registration = Action.async(parse.json.map(_.as[RegisterActivity])) { request =>
    activityService.registerActivity(request.body).map { registration =>
      activityService.findOneById(registration.activityId).onSuccess {
        case Some(activity) =>
          emailService.sendEmail(registration._id.stringify,
            s"[${activity.title}] 有新注册，${registration.name}",
            s"""活动：${activity.title}
                |内容：${activity.content}
                |
                |姓名：${registration.name}
                |电话：${registration.phone}
                |公司：${registration.corporation}
                |职务：${registration.job}
                |
                |注册时间：${registration.createdAt}""".stripMargin)
      }

      Ok(Json.toJson(registration))
    }
  }
}
